﻿using BillHelper;
using DemoForBillOcr;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Management;
using System.Text;
using TaxAssistantBase;

namespace ShiBieProject
{
    public  class InvoiceOcrTool
    {
        private string batchCompanyName = "";
        private  List<InvoiiceOcrModel> _idIOMList;
        private List<InvoiceSonModel> _idIOMSonList;
        string _batchid;
        public InvoiceOcrTool(string batchid,List<InvoiiceOcrModel> idIOMList, List<InvoiceSonModel>  idIOMSonList)
        {
            this._batchid = batchid;
            this._idIOMList = idIOMList;
            this._idIOMSonList = idIOMSonList;
        }

        public  string BatchCompanyName(int chuliNum)
        {
            if (chuliNum == 2)
            {
                if(this._idIOMList != null && this._idIOMList.Count > 0)
                {
                    batchCompanyName = InvoiceOcrCompanyNameTool.getCompanyName(this._idIOMList, this._idIOMSonList);
                }
              
            }

            return batchCompanyName;
        }

        private  WsdLogger ocrlog = new WsdLogger("OcrLog");

        public  bool DealInvoice()
        {
            if(this._idIOMList == null || this._idIOMList.Count == 0)
            {
                return false;
            }
            try {
                try
                {
                    setisnoDK(this._idIOMSonList);
                    //1.得到公司名称
                    string companyName, taxNo;
                    string companyState = InvoiceOcrCompanyNameTool.getCompanyName(this._idIOMList, this._idIOMSonList, out companyName, out taxNo);

                    //2.1.未得到公司名称 ，所有票都是废票（如果没有票需要创建一个）,只用改状态
                    if (string.IsNullOrEmpty(companyName) || (string.IsNullOrEmpty(taxNo)))
                    {
                        foreach (InvoiiceOcrModel iom in _idIOMList)
                        {
                            //设置废弃
                            setFeiQi(iom, companyState);
                        }
                        companyName = "未识别公司";
                        taxNo = "未识别税号";

                        InvoiceOcrCompanyNameTool.fuzhiCompany(this._idIOMList, companyName, taxNo, companyState);
                    }
                    else //2.2.得到公司名称
                    {
                        InvoiceOcrCompanyNameTool.fuzhiCompany(this._idIOMList, companyName, taxNo, companyState);
                        //2.2.1.循环处理每一张票据
                        //2.2.1.1.销项或进项判断，如果都不是就是废票（如果没有票需要创建一个
                        solaInvoiceInfoHandle.judgementInputBillOrOutputBill(this._idIOMList, companyName, taxNo);
                    }
                }
                catch (Exception ex)
                {
                    WsdLogger.yxlog("error", "完整批次处理报错" + ex.Message + "批次号为：" + this._batchid);
                    return false;
                };
                //对日期格式的校验
                InvoiceDateVerification.InvoiceDateVerific(this._idIOMList);
                //2.2.1.3 核验明细内容在明细内容库中是否存在
                InvoiceDetaileName.VerificationDetaileName(this._idIOMList);
                //进行供应商或客户校验
                VerificationVendorsOrCustomer.VerificationVendorsOrCustomerCompany(this._idIOMList);

                try
                {
                    //对金额校验
                    InvoiceMoneysCheck.moneyChuLi(this._idIOMList);
                }
                catch (Exception ex)
                {
                    WsdLogger.yxlog("error", "对金额的校验报错：" + ex.Message + "批次号为：" + this._batchid);
                    return false;
                };
                //得到最终总状态
                try
                {
                    InvoiceOverallVerification.overallVerification(this._idIOMList);
                }
                catch (Exception ex)
                {
                    WsdLogger.yxlog("error", "得到总状态错误" + ex.Message + "批次号为：" + this._batchid);
                }
                return savePiaoJu(this._idIOMList, this._idIOMSonList);
            }
            catch (Exception ex) {
                WsdLogger.yxlog("error", "识别后处理票据报错" + ex.Message + "批次号为：" + this._batchid);
                return savePiaoJu(this._idIOMList, this._idIOMSonList);
            }
        }

        /// <summary>
        /// 代开
        /// </summary>
        /// <param name="idIOMSonList"></param>
        private  void setisnoDK(List<InvoiceSonModel> idIOMSonList)
        {
            int daik = 0;
            if (idIOMSonList.Count > 0)
            {
                for (int i = 0; i < idIOMSonList.Count; i++)
                {
                    if (idIOMSonList[i].invoiceMark == "DK"|| idIOMSonList[i].gfcompanyname.Contains("税务总局"))
                    {
                        daik++;
                    }
                }
                if (daik != idIOMSonList.Count)
                {
                    for (int j = 0; j < idIOMSonList.Count; j++)
                    {
                        if (idIOMSonList[j].invoiceMark == "DK")
                        {
                            idIOMSonList.RemoveAt(j);
                            j--;
                        }
                    }
                }
            }
        }

 

        //得出公司名称对比度
        public static  int NameXianSiD(string compname, string mainCompName)
        {
            int shouname = 1;
            int biduinum = 0;
            string name = mainCompName.Replace("有限", "");
            if (compname.Length > mainCompName.Length) {
                biduinum = mainCompName.Length;
            } else {
                biduinum = compname.Length;
            }
       
            for (int j = 0; j < biduinum; j++)
            {
                if ((j + 1) < biduinum)
                {
                    string doubleName = Convert.ToString(compname[j]) + Convert.ToString(compname[j + 1]);
                    if (name.Contains(doubleName))
                    {
                        shouname++;
                    }
                }
            }
            return shouname;
        }
       

        public static  void setFeiQi(InvoiiceOcrModel bpmall,string companyState)
        {
            bpmall.stateDesc = "废弃";
            bpmall.billtype = ModelEnum.FAIL;
            bpmall.billtypeDesc = "失败";
            bpmall.state = ModelEnum.FAIL;
            bpmall.companyState = companyState;
        }

        //得出相似度
        public static int getTaxNum(string tempism, string taxnum)
        {
            int number = 0;
            int xiansinum = 0;
            if (tempism.Length > taxnum.Length)
            {
                xiansinum = taxnum.Length;
            }
            else {
                xiansinum = tempism.Length;
            }
            for (int j = 0; j < xiansinum; j++)
            {
                if (taxnum[j] == tempism[j])
                {
                    number++;
                }
            }
            return number;
        }

        private  bool savePiaoJu(List<InvoiiceOcrModel> idIOMList, List<InvoiceSonModel> idIOMSonList)
        {
            string apiurl = ApiUrlList.DATALL;
            List<InvoiiceOcrModel> quchonglist = new List<InvoiiceOcrModel>();
            try
            {
                string mac = getMac();
                bool isAdd = true;
                Random rad = new Random();//实例化随机数产生器rad；
                int suijiID = rad.Next(1000, 10000);//用rad生成大于等于1000，小于等于9999的随机数
                for (int i = 0; i < idIOMList.Count; i++)
                {
             
                
                    //判断是否有子项，如果没有需新建
                    shuJuEndChuL(idIOMList[i], suijiID);
                    idIOMList[i].invoiceinfoall = "";
                    string qrcode = idIOMList[i].invoiceOcrSonLists[0].qrCode;
                    if (!string.IsNullOrEmpty(qrcode)) {
                        string[] qrcodeModel = qrcode.Split(',');
                        if (qrcodeModel.Count() < 3)
                        {
                            idIOMList[i].invoiceOcrSonLists[0].qrCode = "";
                        }
                    }
                    idIOMList[i].mac = mac;
                    idIOMList[i].md5 = suijiID.ToString();

                }
                for (int k = 0; k < idIOMList.Count ; k++) {
                    isAdd = true;
                    if (quchonglist.Count > 0)
                    {
                        if (idIOMList[k].invoiceOcrSonLists!=null) {
                            string invoiceNum = idIOMList[k].invoiceOcrSonLists[0].invoiceNum;
                            foreach (InvoiiceOcrModel itm in quchonglist)
                            {
                                if (invoiceNum == itm.invoiceOcrSonLists[0].invoiceNum && invoiceNum != "")
                                {
                                    isAdd = false;
                                    break;
                                }
                            }
                        }
            
                    }
                    if (isAdd) {
                        quchonglist.Add(idIOMList[k]);
                    }
                           
                }
            }
            catch (Exception ex)
            {
                WsdLogger.yxlog("error", "处理数据，数据报错" + ex.Message);
            }
            try
            {
                if (quchonglist.Count > 0)
                {
                    if (quchonglist[0].companyName == null || quchonglist[0].companyName == "")
                    {
                        for (int i = 0; i < idIOMList.Count; i++)
                        {
                            quchonglist[i].companyName = "未识别公司";
                            quchonglist[i].companyTaxnum = "未识别税号";
                        }
                    }
                    //固定公司商品名称
                    InvoiceDetaileProductNameManage.InvoiceDetaileProductNameManageList(quchonglist);
                    //进行公司的默认税率赋值及销项商品名称赋值
                    SetInvoiceProductNameAndDefaultTaxRate.invoiceProductNameAndDefaultTaxRate(this._idIOMList);
                    forwardingToserver(quchonglist, apiurl);//保存
                }
            }
            catch (Exception ex)
            {
                WsdLogger.yxlog("error", "保存票据信息报错" + ex.Message);
                return false;
            }

            return true;
        }

        //设置税率
        public static  string setTaxLv(decimal slv)
        {
            string slend = "";
            if (slv==0) {
                slend = "0%";
            }
            else if (slv <= 2 && slv > 0)
            {
                slend = "1%";
            }
            else if (slv <= 3&&slv>2)
            {
                slend = "3%";
            }
            else if(slv <= 4 && slv > 3)
            {
                slend = "4%";
            }
            else if (slv <= 5 && slv > 4)
            {
                slend = "5%";
            }
            else if (slv >5 && slv <= 6)
            {
                slend = "6%";
            }
            else if (slv>6&&slv<10) {
                slend = "9%";
            }
            else if (slv > 9 && slv <= 10)
            {
                slend = "10%";
            }
            else if (slv > 10 && slv <= 13)
            {
                slend = "13%";
            }
            else if (slv > 13 && slv <= 16)
            {
                slend = "16%";
            }
            else if (slv > 16 && slv <= 17)
            {
                slend = "17%";
            }
            else if (slv > 17 && slv <= 18)
            {
                slend = "18%";
            }
            return slend;
        }
     

        //传入服务器
        private  void forwardingToserver(List<InvoiiceOcrModel> bpm, string apiurl)
        {
            string tpresult;
            string result = "";
            try
            {
                try {
                    List<InvoiiceOcrModel> newInvoiceList = new List<InvoiiceOcrModel>();
                    int i = 0;
                    foreach (InvoiiceOcrModel iom in bpm)
                    {
                        i++;
                        newInvoiceList = new List<InvoiiceOcrModel>();
                        string companyName = iom.companyName;
                        string companyTaxnum = iom.companyTaxnum;
                        string isProviderOrCustomer = "";
                        if (iom.invoiceOcrSonLists!=null) {
                            isProviderOrCustomer = iom.invoiceOcrSonLists[0].isProviderOrCustomer;
                        }
                        if (companyName == "上海卓顾信息科技有限公司" || companyTaxnum == "913101165964435306" || companyName == "上海卓顾信思科技有限公司" || companyTaxnum == "913101165964435305")
                        {
                            newInvoiceList.Add(iom);
                            if (isProviderOrCustomer == "0")
                            {//销项
                                string name, taxNo;
                                string companyState = InvoiceOcrCompanyNameTool.getCompanyName(newInvoiceList, this._idIOMSonList, out name, out taxNo);
                                if (name != "上海卓顾信息科技有限公司" && name != "上海卓顾信思科技有限公司" && taxNo != "913101165964435306" && taxNo != "913101165964435305")
                                {
                                    newInvoiceList[0].companyName = name;
                                    newInvoiceList[0].companyTaxnum = taxNo;
                                    newInvoiceList[0].invoiceOcrSonLists[0].gfcompanyname = name;
                                    newInvoiceList[0].invoiceOcrSonLists[0].gftaxnumber = taxNo;
                                    newInvoiceList[0].invoiceOcrSonLists[0].isProviderOrCustomer = "1";
                                }
                                else
                                {
                                    newInvoiceList[0].companyName = newInvoiceList[0].invoiceOcrSonLists[0].gfcompanyname;
                                    newInvoiceList[0].companyTaxnum = newInvoiceList[0].invoiceOcrSonLists[0].gftaxnumber;
                                    newInvoiceList[0].invoiceOcrSonLists[0].isProviderOrCustomer = "1";
                                }
                            }
                            result = RestOrcTool.Postlist(out tpresult, newInvoiceList, apiurl);
                        }
                    }
                }
                catch (Exception ex) {
                    WsdLogger.yxlog("error", "保存处理票据报错" +ex.Message + "批次号为："+ bpm[0].batchtime);
                     result = RestOrcTool.Postlist(out tpresult, bpm, apiurl);
                    return;
                }
                if (bpm[0].companyName!= "上海卓顾信息科技有限公司" && bpm[0].companyTaxnum!= "913101165964435306") {
                    result = RestOrcTool.Postlist(out tpresult, bpm, apiurl);
                }
                //ocrlog.Write("批量上传服务器返回信息：" + result);
                WsdLogger.yxlog("error", "批量上传服务器返回信息" + result +"____"+ bpm.Count + "公司名称为：" + bpm[0].companyName + "批次号为：" + bpm[0].batchtime );
            }
            catch (Exception es)
            {
                WsdLogger.yxlog("error", "传服务错误" + es.Message);
                return;
            }
        }
        private  void shuJuEndChuL(InvoiiceOcrModel bpm, int suijiID)
        {
            Random rd = new Random(Guid.NewGuid().GetHashCode());
            string[] img = bpm.imgUrl.Split('\\');
            if (bpm != null)
            {
                if (bpm.invoiceinfoall == "" || bpm.invoiceinfoall == null)
                {
                    bpm.invoiceinfoall = new Random().Next(10000).ToString().PadLeft(4, '0');
                }
                if (bpm.invoiceOcrSonLists != null)
                {
                    if (bpm.invoiceOcrSonLists.Count > 0)
                    {
                        if (bpm.invoiceOcrSonLists[0].invoiceNum == null || bpm.invoiceOcrSonLists[0].invoiceNum == "")
                        {
                           
                            bpm.invoiceOcrSonLists[0].invoiceNum = "0000000000" + rd.Next(10000).ToString().PadLeft(4, '0');
                            bpm.invoiceOcrSonLists[0].infoId = suijiID;
                        }
                        bpm.invoiceOcrSonLists[0].readstate = "0";
                    }
                }
                if (bpm.invoiceOcrDetailedDtoList != null)
                {
                    if (bpm.invoiceOcrDetailedDtoList.Count > 0)
                    {
                        for (int i = 0; i < bpm.invoiceOcrDetailedDtoList.Count; i++)
                        {
                            bpm.invoiceOcrDetailedDtoList[i].invoiceId = suijiID;
                        }
                    }
                }
                if (bpm.invoiceOcrSonLists == null || bpm.invoiceOcrSonLists.Count == 0)
                {
                    bpm.invoiceOcrSonLists = new List<InvoiceSonModel>();
                    InvoiceSonModel im = new InvoiceSonModel();
                    bpm.stateDesc = "废弃";
                    bpm.billtype = ModelEnum.FAIL;
                    bpm.billtypeDesc = "失败";
                    bpm.state = ModelEnum.FAIL;
                    im.moneyAmounts = "0";
                    im.totalMoney = "0";
                    im.taxAmounts = "0";
                    im.taxRate = "";
                    im.readstate = "0";
                    im.infoId = suijiID;
                    im.invoiceNum = "0000000000" + rd.Next(10000).ToString().PadLeft(4, '0');
                    bpm.invoiceOcrSonLists.Add(im);
                }
                if (bpm.invoiceOcrDetailedDtoList == null || bpm.invoiceOcrDetailedDtoList.Count == 0)
                {
                    bpm.invoiceOcrDetailedDtoList = new List<invoiceOcrDetailedModel>();
                    invoiceOcrDetailedModel im = new invoiceOcrDetailedModel();
                    im.moneyAmount = "";
                    im.productName = "";
                    im.invoiceId = suijiID;
                    bpm.invoiceOcrDetailedDtoList.Add(im);
                }
                if (bpm.imgUrl != null)
                {
                    ocrlog.Write("处理图片名称为：" + img[img.Length - 1]);
                }
                else
                {
                    ocrlog.Write("处理图片名称为：");
                }
            }
        }



        private  string getMac()
        {
            string macaddress = AppDomain.CurrentDomain.BaseDirectory + "mac.txt";
            string readmac = "";
            if (File.Exists(macaddress))
            {
                string[] line = File.ReadAllLines(macaddress);
                if (line.Length > 0)
                {
                    readmac = line[0];
                }
                else
                {
                    readmac = getHostIpName();//获取
                }
            }
            else
            {
                readmac = getHostIpName();//获取
            }
            return readmac;
        }
       
        //获取MAC地址
        private  string getHostIpName()
        {
            string mac = "";
            ManagementClass mc;
            mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = mc.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                if (mo["IPEnabled"].ToString() == "True")
                    mac = mo["MacAddress"].ToString();
            }
            return mac;
        }
    }
}
